package cn.iocoder.yudao.module.cmt.service.course;

import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import cn.iocoder.yudao.module.cmt.controller.admin.course.vo.*;
import cn.iocoder.yudao.module.cmt.dal.dataobject.course.CourseChapterDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.cmt.dal.mysql.course.CourseChapterMapper;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.cmt.enums.ErrorCodeConstants.*;

@Service
@Validated
public class CourseChapterServiceImpl implements CourseChapterService {

    @Resource
    private CourseChapterMapper courseChapterMapper;

    @Override
    public Long createCourseChapter(CourseChapterSaveReqVO createReqVO) {
        CourseChapterDO courseChapter = BeanUtils.toBean(createReqVO, CourseChapterDO.class);
        courseChapterMapper.insert(courseChapter);
        return courseChapter.getId();
    }

    @Override
    public void updateCourseChapter(CourseChapterSaveReqVO updateReqVO) {
        validateCourseChapterExists(updateReqVO.getId());
        CourseChapterDO updateObj = BeanUtils.toBean(updateReqVO, CourseChapterDO.class);
        courseChapterMapper.updateById(updateObj);
    }

    @Override
    public void deleteCourseChapter(Long id) {
        validateCourseChapterExists(id);
        courseChapterMapper.deleteById(id);
    }

    private void validateCourseChapterExists(Long id) {
        if (courseChapterMapper.selectById(id) == null) {
            throw exception(COURSE_CHAPTER_NOT_EXISTS);
        }
    }

    @Override
    public CourseChapterDO getCourseChapter(Long id) {
        return courseChapterMapper.selectById(id);
    }

    @Override
    public PageResult<CourseChapterDO> getCourseChapterPage(CourseChapterPageReqVO pageReqVO) {
        return courseChapterMapper.selectPage(pageReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteCourseChapterListByIds(List<Long> ids) {
        ids.forEach(this::validateCourseChapterExists);
        courseChapterMapper.deleteBatchIds(ids);
    }

}
